import { reactive, toRefs, provide, readonly, ref } from 'vue';
import { useLoad } from '@tarojs/taro';
import { afterLogin, useRouter } from '.';
import { loadingKey } from '@/constants';

export const useLoading = callback => {
  const state = reactive({ loading: true, options: null, data: null });
  const loading = reactive({
    errorMsg: null
  });
  const router = useRouter();
  const restart = async (delay = 0) => {
    loading.errorMsg = null;
    state.loading = true;
    if (delay) await Promise.sleep(delay);
    try {
      await callback(state.options, state.data);
    } catch (e) {
      loading.errorMsg = e.message;
      state.loading = false;
      throw e;
    }
    state.loading = false;
  };
  loading.restart = restart;
  provide(loadingKey, readonly(loading));

  useLoad(async options => {
    state.data = await router.getData();
    await afterLogin();
    state.options = options;
    await restart();
  });
  return {
    restart,
    ...toRefs(state)
  };
};
